//
//  ViewController.swift
//  DMCamera
//
//  Created by 李浩 on 2017/8/3.
//  Copyright © 2017年 李浩. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var device: AVCaptureDevice?
    var input: AVCaptureDeviceInput?
    var imageOutput: AVCaptureStillImageOutput!
    var session: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!

    let d_width = UIScreen.main.bounds.width
    let d_height = UIScreen.main.bounds.height
    
    var imageV: UIImageView!;
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        configcamera()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        session.startRunning()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        session.stopRunning()
    }
    
    func configcamera() {
        device = cameraWithPosition(position: .back)
        if (device != nil) {
            do {
                try input = AVCaptureDeviceInput(device: device)
            } catch {
                
            }
            if (input != nil) {
                imageOutput = AVCaptureStillImageOutput()
                session = AVCaptureSession()
                session.sessionPreset = AVCaptureSessionPreset640x480
                if (session.canAddInput(input)) {
                    session.addInput(input)
                }
                if (session.canAddOutput(imageOutput)) {
                    session.addOutput(imageOutput)
                }
                
                previewLayer = AVCaptureVideoPreviewLayer(session: session)
                let layerW = d_width - 20
                let layerH = (d_width - 20) * (480 / 320.0)
                previewLayer.frame = CGRect(x: 10, y: 10, width: layerW, height: layerH)
                view.layer.addSublayer(previewLayer)
                
                do {
                    try device!.lockForConfiguration()
                    if (device?.isFlashModeSupported(.auto) == true) {
                        device?.isFlashModeSupported(.auto)
                    }
                    if (device?.isWhiteBalanceModeSupported(.autoWhiteBalance) == true) {
                        device?.isWhiteBalanceModeSupported(.autoWhiteBalance)
                    }
                    device?.unlockForConfiguration()
                } catch {
                
                }
                
                let cameraBtn = UIButton(type: .custom)
                cameraBtn.frame = CGRect(x: (d_width - 50) / 2.0, y: layerH + 60, width: 50, height: 50)
                cameraBtn.addTarget(self, action: #selector(ViewController.cameraClick), for: .touchUpInside)
                cameraBtn.backgroundColor = UIColor.orange
                view.addSubview(cameraBtn)
            }
        }
        
        imageV = UIImageView(frame: CGRect(x: 0, y: d_height - 60, width: 60 * (320 / 480.0), height: 60))
        view.addSubview(imageV)
    }
    
    func cameraClick() {
        let conntion = imageOutput.connection(withMediaType: AVMediaTypeVideo)
        if conntion == nil {
            print("失败")
            return
        }
        imageOutput.captureStillImageAsynchronously(from: conntion) { (imageDataSamplebuffer, error) in
            if (imageDataSamplebuffer == nil) {
                return
            }
            if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSamplebuffer) {
                self.imageV.image = UIImage(data: imageData)
            }
        }
    }
    
    
    func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
        if let devices: [AVCaptureDevice] = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] {
            for device in devices {
                if (device.position == position) {
                    return device
                }
            }
        }
        return nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

